import React, { useRef, useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Button, message, Space, Table, Tag, Tooltip, Divider } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { resourcepage, resourceDelete } from '@/services/system/resource';
import { useOutletContext } from '@umijs/max';
import AuthorizedButton from '@/components/AuthorizedButton';
interface ButtonData {
  id: string;
  pageId: string;
  resourceName: string;
  icon?: string;
  action: string;
}
const ResourceManageList: React.FC = () => {
  const [records, setRecords] = useState<any[]>([]);
  const { buttonData } = useOutletContext<{ buttonData: ButtonData[] }>();
  console.log('buttonData,ziyuanguanl ', buttonData);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const navigate = useNavigate();


  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async (params = {}) => {
    try {
      const response = await resourcepage({
        current: params?.current || 1,
        size: params?.pageSize || 10,
        ...params
      });
      if (response.code === 200) {
        setRecords(response.data.records);
        setPagination({
          current: response.data.current,
          pageSize: response.data.size,
          total: response.data.total,
        });
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 资源类型转译
  const getResourceType = (type: string) => {
    const typeMap: Record<string, { text: string; color: string }> = {
      'menu': { text: '菜单', color: 'blue' },
      'page': { text: '页面', color: 'purple' },
      'button': { text: '按钮', color: 'green' },
      'api': { text: '接口', color: 'orange' },
    };
    return typeMap[type] || { text: type, color: 'default' };
  };

  // 状态转译
  const getStatusText = (status: number) => {
    const statusMap: Record<number, { text: string; color: string }> = {
      0: { text: '正常', color: 'success' },
      1: { text: '禁用', color: 'error' },
    };
    return statusMap[status] || { text: '未知', color: 'default' };
  };

  // 是否显示转译
  const getVisibleText = (visible: number) => {
    const visibleMap: Record<number, { text: string; color: string }> = {
      1: { text: '显示', color: 'success' },
      0: { text: '隐藏', color: 'default' },
    };
    return visibleMap[visible] || { text: '未知', color: 'default' };
  };

  const columns = [
    {
      title: '资源名称',
      dataIndex: 'resourceName',
      ellipsis: true,

    },
    {
      title: '资源别名',
      dataIndex: 'alias',
      ellipsis: true,

    },
    {
      title: '资源类型',
      dataIndex: 'resourceType',

      render: (type: string) => {
        const { text, color } = getResourceType(type);
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '路由地址',
      dataIndex: 'path',
      ellipsis: true,

      render: (path: string) => (
        <Tooltip placement="topLeft" title={path}>
          <span>{path}</span>
        </Tooltip>
      ),
    },
    {
      title: '排序',
      dataIndex: 'sort',

      align: 'center' as const,
    },
    {
      title: '是否显示',
      dataIndex: 'visible',

      align: 'center' as const,
      render: (visible: number) => {
        const { text, color } = getVisibleText(visible);
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '资源状态',
      dataIndex: 'status',

      align: 'center' as const,
      render: (status: number) => {
        const { text, color } = getStatusText(status);
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',

      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <span>
        <Space split={<Divider type="vertical" />}>
          <AuthorizedButton
            buttonData={buttonData}
            action="edit"
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            编辑
          </AuthorizedButton>
          <AuthorizedButton
            buttonData={buttonData}
            action="delete"
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
              // backgroundColor:'red'
            }}
          >
            删除
          </AuthorizedButton>
          <AuthorizedButton
            buttonData={buttonData}
            action="view"
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            详情
          </AuthorizedButton>
        </Space>
      </span>
      ),
    },
  ];

  const handleAdd = () => {
    navigate('/system/resourcemanage/add');
  };

  const handleEdit = (record) => {
    navigate('/system/resourcemanage/edit', { state: { record } });
  };

  const handleDelete = async (record) => {
    try {
      const response = await resourceDelete({ id: record.id });
      if (response.code === 200) {
        message.success('删除成功');
        fetchData();
      } else {
        message.error(response.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const handleView = (record) => {
    navigate('/system/resourcemanage/view', { state: { record } });
  };

  return (
    <PageContainer>
      <Space style={{ marginBottom: 16 }}>
        <AuthorizedButton
          buttonData={buttonData}
          action="add"
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          新增资源
        </AuthorizedButton>
      </Space>
      <Table
        columns={columns}
        dataSource={records}
        rowKey="id"
        scroll={{ x: 'max-content' }}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (page, pageSize) => {
            fetchData({ current: page, size: pageSize });
          },
        }}
        tableLayout="auto"
      />
    </PageContainer>
  );
};

export default ResourceManageList;
